package com.duubee.btframe.utils;

import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class BtStreamUtil {

    public static InputStream byte2Input(byte[] buf) {
        return new ByteArrayInputStream(buf);
    }

    public static byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }

    /**
     * 将str转换为inputStream
     *
     * @param str
     * @return
     */
    public static InputStream str2InputStream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }

    /**
     * 将inputStream转换为str
     *
     * @param inputStream
     * @return
     */
    public static String inputStream2Str(InputStream inputStream) {
        StringBuffer sb;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(inputStream));
            sb = new StringBuffer();
            String data;
            while ((data = br.readLine()) != null) {
                sb.append(data);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将file转换为inputStream
     *
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public static InputStream file2InputStream(File file) throws FileNotFoundException {
        return new FileInputStream(file);
    }

    /**
     * 将inputStream转化为file
     *
     * @param is
     * @param file 要输出的文件目录
     */
    public static void inputStream2File(InputStream is, File file) throws IOException {
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int len = 0;
            byte[] buffer = new byte[8192];

            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } finally {
            os.close();
            is.close();
        }
    }

    /**
     * 文本写到文件
     *
     * @param file
     * @param str
     * @throws IOException
     */
    public static void writeStrToFile(File file, String str) throws IOException {
        FileWriter writer = new FileWriter(file);
        writer.write(str);
        writer.flush();
        writer.close();
    }

    /**
     * 通过文件路径读取文件内容
     * @param path 文件路径
     * @return 文件内容
     * @throws IOException io异常
     */
    public static String readContentByPath(String path) throws IOException {
        FileReader fr = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            fr = new FileReader(path);
            int ch = fr.read();
            while (ch != -1) {
                stringBuilder.append((char) ch);
                ch = fr.read();
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (fr != null)
                    fr.close();
            } catch (IOException e) {

            }
        }

    }

    /**
      * 将文件转成base64 字符串
      * @param file 文件对象
      * @return
      * @throws Exception

     */
    public static String encodeBase64File(File file) throws Exception {
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);

    }

    /**
     * 根据byte数组，生成文件
     * filePath  文件路径
     * fileName  文件名称（需要带后缀，如*.jpg、*.java、*.xml）
     */
    public static void byteToFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            //判断文件目录是否存在
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取文件指定行
     *
     * @param sourceFile
     * @param lineNumber
     * @return
     * @throws IOException
     */
    public static List<String> readControllerLineNumber(File sourceFile, int lineNumber) throws IOException {
        FileReader in = new FileReader(sourceFile);
        LineNumberReader reader = new LineNumberReader(in);
        List<String> result = new ArrayList<>();
        String s = null;
        int line = 1;

        reader.setLineNumber(lineNumber);
        long i = reader.getLineNumber();
        while (reader.readLine() != null) {
            if (i == line) {
                result.add(reader.readLine());
                break;
            }
            line++;
        }


        reader.close();
        in.close();
        return result;

    }
}
